package com.huifaapp.mall.selectImage;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.huifaapp.mall.APP;

public abstract class BaseFragment extends Fragment {
	protected View fragmentView;
	protected Activity baseActivity;
	protected TTKFragmentBroadcast ttkFragmentBroadcast;

	protected class TTKFragmentBroadcast extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			onTTKFragmentReceive(context, intent);
		}
	}

	/**
	 * 注册一个fragment广播
	 * @param action 需要监听的ACTION
	 */
	protected void registerTTKFragmentBroadcast(String action){
		if (ttkFragmentBroadcast == null) {
			ttkFragmentBroadcast = new TTKFragmentBroadcast();
		}
		IntentFilter intentFilter = new IntentFilter(action);
		baseActivity.registerReceiver(ttkFragmentBroadcast, intentFilter);
	}

	protected void onTTKFragmentReceive(Context context, Intent intent) {}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (getLayoutId() != 0) {
			fragmentView = inflater.inflate(getLayoutId(), container, false);
		}
		
		baseActivity = getActivity();
		initialize();
		initView();
		
		return fragmentView;
	}
	
	public View findViewById(int id) {
		if (fragmentView == null) {
			System.err.println(this.getClass().getSimpleName() + " fragmentView isNull");
			return null;
		}
		return fragmentView.findViewById(id);
	}

	public void sendTTKBroadcast(Intent intent) {
		baseActivity.sendBroadcast(intent);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (ttkFragmentBroadcast != null) {
			baseActivity.unregisterReceiver(ttkFragmentBroadcast);
		}
	}

	/**
	 * 布局ID
	 * @return
	 */
	public abstract int getLayoutId();
	/**
	 * 初始化操作 如请求网络数据
	 */
	protected abstract void initialize();
	
	/**
	 * 初始化控件
	 */
	protected abstract void initView();

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void startActivity(Intent intent) {
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		super.startActivity(intent); 
	}

	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		super.startActivityForResult(intent, requestCode);
	}
	
	@Override
	public void setMenuVisibility(boolean menuVisible) {
		super.setMenuVisibility(menuVisible);
		if (this.getView() != null) {
			if (menuVisible) {
				this.getView().setVisibility(View.VISIBLE);
			} else {
				this.getView().setVisibility(View.GONE);
			}
		}
	}
}
